<?php
namespace App\Admin\Controllers\Purchase;

use App\Models\Product\ProductClassify;
use App\Models\Stocking\StockingApplyDetail;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Support\Facades\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;
class PlanController extends AdminController{

    protected $title = '采购计划下单';

    protected $filters = [
        'sku' => null,
        'stocking_no' => null,
        'classify_id' => null,
    ];

    protected $headersField = [
        'psku_code',
        'title',
        'apply_detail_num',
        'plan_num',
        'psku_cn',
    ];

    protected function grid()
    {
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $this->_initFilters($filters);
        $query = $this->_initQuery($filters);
        $_query = clone $query;
        $paginator = $this->_paginator($query);
        $total = $this->_sum($_query);
        $action = getAction($filtersField);
        $filtersBlade = [];
        $filtersBlade['sku'] = $this->filters['sku'];
        $filtersBlade['stocking_no'] = $this->filters['stocking_no'];
        $filtersBlade['classify_id'] = getOptions(ProductClassify::options(),$this->filters['classify_id']);
        $downloadUrl = '/xqc/purchase/plan-download?' . http_build_query(array_merge(Request::all(),['_export_' => true]));
        $headers = $this->headersField;
        return view('purchase.plan.index', compact('paginator','total','headers','action','filtersBlade','downloadUrl'));
    }

    private function _getFilters($filtersField){
        $filters = [];
        foreach ($filtersField as $field){
            $filters[$field] = request($field);
        }
        return $filters;
    }

    private function _initFilters($filters){
        foreach ($filters as $field => $filter){
            $this->filters[$field] = $filter;
        }
    }

    private function _initQuery($filters){
        //备货申请明细
        $query = StockingApplyDetail::query()
            ->where('plan_status','<>',3) //完全计划
            ->where('status',1) //已审核
            ->orderByDesc('id');
        foreach ($filters as $field => $filter){
            if(!$filter)continue;
            if($field == 'sku'){
                $query->whereHas('sku', function ($query) use($filter){
                    $query->where('psku_code', 'like', "%{$filter}%")
                        ->orWhere('psku_cn', 'like', "%{$filter}%");
                });
            }
            if($field == 'stocking_no'){
                $query->where(function ($query) use($filter){
                    $query->where('stocking_no', $filter);
                });
            }
            if($field == 'classify_id'){
                $query->whereHas('sku', function ($query) use($filter){
                    $query->where('classify_id', $filter);
                });
            }
        }
        return $query;
    }

    private function _sum($query){
        $sum = $query->selectRaw('1,'.$this->__getSumFields())->groupBy(1)->first();
        return $sum ? $sum->toArray() : $this->__getSumFieldsInit();
    }

    private function _paginator($query){
        $query->selectRaw('psku_id,'.$this->__getSumFields())->groupBy('psku_id')->orderBy('psku_id', 'DESC');
        return $query->paginate((int) (request("per_page",10)))->appends(Request::input());
    }

    private function __getSumFields(){
        $re = 'sum(apply_detail_num) as apply_detail_num';
        $re .= ',sum(plan_num) as plan_num';
        return $re;
    }

    private function __getSumFieldsInit(){
        return ['apply_detail_num' => 0,'plan_num' => 0];
    }

    public function download(){
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $query = $this->_initQuery($filters);
        $query->selectRaw('psku_id,'.$this->__getSumFields())->groupBy('psku_id');
        $this->_exeDownload($query);
    }

    private function _exeDownload($query){
        $head = ['SKU','品类','备货数量','已计划采购','产品名称'];
        set_time_limit(0);
        $response = new StreamedResponse(null, 200, [
            'Content-Type'        => 'text/csv;charset=utf-8',
            'Content-Disposition' => 'attachment;filename="采购计划.csv"',
        ]);
        $response->setCallback(function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->orderBy('psku_id', 'DESC')->chunk(50, function ($re) use ($fp){
                $data = $this->__getData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
        });
        $response->send();
        exit(0);
    }

    private function __getData($re)
    {
        foreach ($re as $row){
            $temp = [];
            $temp['psku_code'] = $row->sku->psku_code ?? '';
            $temp['title'] = $row->sku->classify->title ?? '';
            $temp['apply_detail_num'] = $row->apply_detail_num;
            $temp['plan_num'] = $row->plan_num;
            $temp['psku_cn'] = $row->sku->psku_cn ?? '';
            yield $temp;
        }
    }
}
